using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using DealerPlatform.Common.EventBusHelper;
using DealerPlatform.Core.Repository;
using DealerPlatform.Domain;
using DealerPlatform.Service.ShoppingCartApp.Dto;
using Microsoft.EntityFrameworkCore;

namespace DealerPlatform.Service.ShoppingCartApp
{
    public partial class ShoppingCartService : IShoppingCartService
    {
        public ShoppingCartService(
            IRepository<ShoppingCart> repoShoppingCart,
            IMapper mapper,
            LocalEventBus<List<ShoppingCartDto>> localEventBus
        )
        {
            RepoShoppingCart = repoShoppingCart;
            Mapper = mapper;
            LocalEventBus = localEventBus;
        }

        public IRepository<ShoppingCart> RepoShoppingCart { get; }
        public IMapper Mapper { get; }
        public LocalEventBus<List<ShoppingCartDto>> LocalEventBus { get; }

        public async Task<ShoppingCartDto> SetShoppingCart(ShoppingCartInputDto shoppingCart){
            ShoppingCart cart = Mapper.Map<ShoppingCart>(shoppingCart);
            cart.CartGuid = Guid.NewGuid().ToString();
            cart.CartSelected = true;
            cart = await RepoShoppingCart.InsertAsync(cart);
            return Mapper.Map<ShoppingCartDto>(cart);
        }

        public async Task<List<ShoppingCartDto>> GetShoppingCartDto(string customerNo){
            List<ShoppingCart> carts = await RepoShoppingCart.GetQueryable().Where(p=>p.CustomerNo == customerNo).ToListAsync(); 
            var dtos = Mapper.Map<List<ShoppingCart>,List<ShoppingCartDto>>(carts);
            await LocalEventBus.Publish(dtos);
            return dtos;
        }
    }
}